package org.study.security.utils;

import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import org.study.base.utils.BaseResult;
import org.study.base.utils.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: securityparent
 * @description: 退出处理
 * @author: lishuang
 * @create: 2021-12-03 16:52
 **/
@Component
public class LogoutTokenHandler implements LogoutHandler {

    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    RedisTemplate redisTemplate;

    public LogoutTokenHandler(TokenUtil tokenUtil, RedisTemplate redisTemplate) {
        this.tokenUtil = tokenUtil;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        //1 从header获取token
        String token = httpServletRequest.getHeader("token");

        //2 token不为空 移除token 从redis删除
        if (token!=null){
            tokenUtil.removeToken(token);

            //从redis删除
            String username = tokenUtil.getUserInfoFromToken(token);
            redisTemplate.delete(username);
        }
        ResponseUtil.out(httpServletResponse, BaseResult.ok());
    }
}
